package com.tinem.platform.web.auth.server.client.token;

import com.tinem.platform.module.pojo.co.JwtPropertyName;
import com.tinem.platform.module.starter.jpa.entity.oauth.UserSessionToken;
import com.tinem.platform.module.starter.jpa.repository.oauth2.UserSessionTokenRepository;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className PlatformTokenEnhancer
 * @description TODO
 * @site 
 * @company 
 * @create 2020-08-31 13:59
 */
public class PlatformSaveTokenEnhancer implements TokenEnhancer {

    UserSessionTokenRepository userSessionTokenRepository;

    public PlatformSaveTokenEnhancer(UserSessionTokenRepository userSessionTokenRepository) {
        this.userSessionTokenRepository = userSessionTokenRepository;
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {


        UserSessionToken userSessionToken = new UserSessionToken();
        userSessionToken.setId(String.valueOf(accessToken.getAdditionalInformation().getOrDefault(JwtPropertyName.JTI,"")));
        userSessionToken.setJwt(accessToken.getValue());
        userSessionToken.setUserId(String.valueOf(accessToken.getAdditionalInformation().getOrDefault(JwtPropertyName.USER_ID,"")));
        userSessionToken.setClientId(authentication.getOAuth2Request().getClientId());
        userSessionToken.setExp(accessToken.getExpiration());
        userSessionTokenRepository.saveAndFlush(userSessionToken);
        return accessToken;
    }
}
